/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.testis.gui.mvc.view.labels;

import org.testis.utils.tree.DefaultMutableLabelNode;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author selcuk
 */
public class DefaultLabelJTree extends JTree {

    public DefaultLabelJTree(DefaultMutableLabelNode root) {
        super();
        initLabelTree();
        refreshLabelTree(getLabelTreeModel(root));
    }

    public DefaultLabelJTree() {
        super();
        initLabelTree();
        refreshLabelTree(getLabelTreeModel());
    }

    public void loadLabels(DefaultMutableLabelNode root) {
        refreshLabelTree(getLabelTreeModel(root));
    }

    private void initLabelTree() {
        setModel(new DefaultTreeModel(null));
        setCellRenderer(new DefaultLabelNodeRenderer());
    }

    private DefaultMutableLabelNode loadLabelTree() {
        ILabelTreeLoader treeLoader = new DefaultLabelTreeLoader();
        DefaultMutableLabelNode root = treeLoader.loadTree();
        return root;
    }

    private DefaultTreeModel getLabelTreeModel() {
        DefaultMutableLabelNode root = loadLabelTree();
        return new DefaultTreeModel(root);
    }

    private DefaultTreeModel getLabelTreeModel(DefaultMutableLabelNode root) {
        return new DefaultTreeModel(root);
    }

    private void refreshLabelTree(DefaultTreeModel model) {
        setModel(model);
        updateUI();
        expand();
    }

    private void expand() {
        for (int i = 0; i < getRowCount(); i++) {
            expandRow(i);
        }
    }

    public DefaultMutableLabelNode getSelectedNode() {
        DefaultMutableLabelNode currentNode = null;
        TreePath currentSelection = getSelectionPath();
        if (currentSelection != null) {
            currentNode = (DefaultMutableLabelNode) (currentSelection.getLastPathComponent());
        }
        return currentNode;
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                JFrame frame = new JFrame("Demo");
                frame.getContentPane().add(new DefaultLabelJTree());
                frame.pack();
                frame.setVisible(true);
            }
        });
    }

}
